package com.zjh.jdqlib.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.coder.vincent.smart_toast.SmartToast
import com.drake.channel.receiveEvent
import com.wuhao.jdqlib.data.BleBlulletEvent
import com.wuhao.jdqlib.interf.JdqCallback
import com.wuhao.jdqlib.ui.BleListActivity
import com.wuhao.jdqlib.utils.JdqLibUtil
import com.wuhao.jdqlib.utils.throttleClick
import com.zjh.jdqlib.R

class MainActivity : AppCompatActivity() {
    val jdqLibUtil = JdqLibUtil(this, this@MainActivity)
    var dataStr:TextView? = null
    var status:TextView? = null

    // 创建一个ActivityResultLauncher来启动蓝牙开启请求
    private val enableBtLauncher=
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                // 用户同意开启了蓝牙
                //蓝牙列表
                startActivity(Intent(this@MainActivity, BleListActivity::class.java))
            } else {
                // 用户拒绝开启蓝牙
                SmartToast.emotion().warning(com.wuhao.jdqlib.R.string.ble_permission_disagree)
            }
        }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        //初始化蓝牙
        jdqLibUtil.initBlue(enableBtLauncher)
        //绑定控件
        dataStr = findViewById<TextView>(R.id.data)
        status = findViewById<TextView>(R.id.status)
        findViewById<Button>(R.id.intent).throttleClick {
            startActivity(Intent(this@MainActivity,NouiActivity::class.java))
        }
        //打开蓝牙-点击事件
        findViewById<Button>(R.id.open).throttleClick {
            jdqLibUtil.openBluetooth()
        }
        //关闭蓝牙-点击事件
        findViewById<Button>(R.id.stop).throttleClick {
            jdqLibUtil.disConnect()
        }
        //接收
        receiveEvent<BleBlulletEvent>{
            Log.e("zjh","${it.jdqNumber}")
        }
        jdqLibUtil.registerCallBack(object :JdqCallback{
            override fun onBlueConnected() {
                status?.text = "onBlueConnected"
            }

            override fun onBlueDisconnected() {
                status?.text = "onBlueDisconnected"
            }

            override fun onDataReceived(data: String) {
                dataStr?.text = "$data"
            }

            override fun onError(error: String) {
                dataStr?.text = "$error"
            }

        })
    }

    /**
     * 销毁
     */
    override fun onDestroy() {
        super.onDestroy()
        jdqLibUtil.cleanResource()
    }

}